package Thread;/*
 *
 *@author:    Xavier
 *@data:      2024 - 01 - 13
 *@time:      17:04
 *
 */

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

//基于阻塞队列 实现生产者-消费者模型
public class Demo19 {
    public static void main(String[] args) {
        //阻塞队列
        BlockingDeque<Integer> queue = new LinkedBlockingDeque<>();

        //生产
        Thread t1 = new Thread(() -> {
            int count = 0;
            while (true) {
                try {
                    queue.put(count);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("Product elem : " + count);
                ++count;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        //消费
        Thread t2 = new Thread(() -> {
           while (true) {
               try {
                   Integer n = queue.take();
                   System.out.println("Cost elem: " + n);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        });

        t1.start();
        t2.start();
    }
}
